//
//  YCPowerSearchViewController.m
//  LOLBox
//
//  Created by mac on 15-4-1.
//  Copyright (c) 2015年 Honey. All rights reserved.
//

#import "YCPowerSearchViewController.h"
#import "HttpRequestManager.h"
#import "YCPickerViewController.h"
#import "YCPowerModel.h"
#import "UIViewController+CWPopup.h"
#import "DataBaseSImple.h"

@interface YCPowerSearchViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *name;
@property (nonatomic, strong) NSString *serName;
@property (nonatomic, strong) NSString *fName;
@property (weak, nonatomic) IBOutlet UIImageView *bgImgView;


@end

@implementation YCPowerSearchViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self createNavTitleView:@"添加关注"];
        self.navigationItem.leftBarButtonItem = [[UIBarButtons alloc] createCancelBarButtonWithTarget:self WithAction:@selector(dissView)];
        self.name.delegate = self;
    }
    return self;
}

- (void)dissView
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField endEditing:YES];
    return YES;
}
- (IBAction)onClickServer:(UIButton *)sender
{
    [self hideKey];
    //弹出菜单
    
    YCPickerViewController *pk = [[YCPickerViewController alloc] initWithNibName:@"YCPickerViewController" bundle:nil];

    self.modalPresentationStyle = UIModalPresentationCustom;
    
    [pk getServerName:^(NSString *serName, NSString *fName) {
        [sender setTitle:[NSString stringWithFormat:@"%@ %@",fName,serName] forState:UIControlStateNormal];
        _serName = serName;
        _fName = fName;
    }];
    [self.navigationController presentPopupViewController:pk animated:YES completion:nil];
    
    pk.dissBlock = ^(){
        [self dismissPopup];
    };
}
//关闭弹出菜单
- (void)dismissPopup {
    if (self.navigationController.popupViewController != nil) {
        [self.navigationController dismissPopupViewControllerAnimated:YES completion:^{
            NSLog(@"popup view dismissed");
        }];
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKey)];
    [self.bgImgView addGestureRecognizer:tap];
    [self createKeyBoard];
}
- (void)hideKey
{
    [self.view endEditing:YES];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    NSLog(@"进入编辑");
    return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    NSLog(@"结束编辑");
    return YES;
}

- (void)createKeyBoard
{
    //使用通知中心来获取键盘的弹出
    //1.打开收音机 -- 获取NSNotificationCenter实例
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    
    //2.调整频率，收听想要听的节目  -- 监听指定广播
    //3.接收到通知之后要做的事情
    [center addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [center addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyBoardWillHide:(NSNotification *)info
{
    [UIView animateWithDuration:0.25 animations:^{
        self.view.frame = CGRectMake(0, 64, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame));
    }];
}

- (void)keyBoardWillShow:(NSNotification *)info
{
//    NSLog(@"info = %@", info);
    
    //获取当前触发键盘的文本框对象
    //UITextField *textField = info.object;
    
    //获取键盘信息
    NSDictionary *keyBoardInfo = info.userInfo;
    
    //获取
    NSValue *rectValue = keyBoardInfo[UIKeyboardFrameEndUserInfoKey];
    //将NSValue --> CGRect
    //1.准备一个空的CGRect变量
    CGRect keyBoardFrame;
    
    //2.将该变量交给NSValue对象
    [rectValue getValue:&keyBoardFrame];
    
    //修改当前view的y坐标
    NSInteger offset = self.view.frame.size.height - keyBoardFrame.origin.y;
    
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y = -offset;
    
    [UIView animateWithDuration:0.25 animations:^{
        self.view.frame = viewFrame;
    }];
    
    
//    NSLog(@"keyBoardFrame = %@", NSStringFromCGRect(keyBoardFrame));
    
}


- (IBAction)onClick:(UIButton *)sender
{
    [self.name resignFirstResponder];
    
    //首先判断数据库中是否有了这个用户名
    __block BOOL isHave = NO;
    NSMutableArray *arr = [NSMutableArray array];
    [arr addObjectsFromArray:[[DataBaseSimple shareInstance] selectFromDB]];
    [arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        YCPowerModel *mo = obj;
        
        NSLog(@"%@  -  %@",mo.zone,mo.name);
        NSLog(@"%@  -  %@",_serName,_name.text);
        if ([mo.server isEqualToString:_fName] && [mo.name isEqualToString:_name.text])
        {
            NSLog(@"用户已存在");
            isHave = YES;
            YCLoadingVIew *sucee = [[YCLoadingVIew alloc] initWithFrame:self.view.bounds withTitle:@"用户已存在"];
            [self.view addSubview:sucee];
            [UIView animateWithDuration:2 animations:^{
                sucee.alpha = 0;
            } completion:^(BOOL finished) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }];
        }
    }];
    
    // 如果没有，就查找
    if (!isHave)
    {
        NSLog(@"查找");
        
        YCLoadingVIew *load = [[YCLoadingVIew alloc] initWithFrame:self.view.bounds withTitle:@"正在添加"];
        [self.view addSubview:load];
        
        [[HttpRequestManager shareInstance] downloadZHLWithName:self.name.text withServerName:_serName withFName:_fName withIsSuccess:^(BOOL isSi) {
            NSLog(@"-- %d",isSi ? YES:NO);
            [load removeFromSuperview];
            if (isSi)
            {
                YCLoadingVIew *sucee = [[YCLoadingVIew alloc] initWithFrame:self.view.bounds withTitle:@"添加成功"];
                [self.view addSubview:sucee];
                [UIView animateWithDuration:2 animations:^{
                    sucee.alpha = 0;
                } completion:^(BOOL finished) {
                    [self dismissViewControllerAnimated:YES completion:nil];
                    
                }];
            }
            else
            {
                YCLoadingVIew *sucee = [[YCLoadingVIew alloc] initWithFrame:self.view.bounds withTitle:@"信息有误"];
                [self.view addSubview:sucee];
                [UIView animateWithDuration:2 animations:^{
                    sucee.alpha = 0;
                }];
            }
        }];
        
        //[self dissView];

    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
